// 获取DOM元素
const taskInput = document.getElementById('taskInput');
const addTaskBtn = document.getElementById('addTaskBtn');
const taskList = document.getElementById('taskList');
const taskCount = document.getElementById('taskCount');
const clearCompletedBtn = document.getElementById('clearCompletedBtn');
const filterBtns = document.querySelectorAll('.filter-btn');

// 状态管理
let tasks = [];
let currentFilter = 'all';
let editingTaskId = null;

// 初始化应用
function initApp() {
    loadTasks();
    renderTasks();
    updateStats();
    setupEventListeners();
}

// 从localStorage加载任务
function loadTasks() {
    const savedTasks = localStorage.getItem('todos');
    if (savedTasks) {
        tasks = JSON.parse(savedTasks);
    }
}

// 保存任务到localStorage
function saveTasks() {
    localStorage.setItem('todos', JSON.stringify(tasks));
}

// 渲染任务列表
function renderTasks() {
    taskList.innerHTML = '';
    
    // 根据当前过滤器筛选任务
    const filteredTasks = tasks.filter(task => {
        if (currentFilter === 'active') return !task.completed;
        if (currentFilter === 'completed') return task.completed;
        return true;
    });
    
    if (filteredTasks.length === 0) {
        const emptyState = document.createElement('div');
        emptyState.className = 'empty-state';
        emptyState.textContent = currentFilter === 'all' ? '还没有任务，添加一个吧！' : 
                              currentFilter === 'active' ? '没有进行中的任务' : '没有已完成的任务';
        taskList.appendChild(emptyState);
        return;
    }
    
    // 为每个任务创建DOM元素
    filteredTasks.forEach(task => {
        const li = document.createElement('li');
        li.className = `task-item ${task.completed ? 'completed' : ''}`;
        li.setAttribute('data-id', task.id);
        li.setAttribute('draggable', 'true');
        
        // 设置拖拽属性
        li.addEventListener('dragstart', handleDragStart);
        li.addEventListener('dragover', handleDragOver);
        li.addEventListener('drop', handleDrop);
        
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.className = 'checkbox';
        checkbox.checked = task.completed;
        checkbox.addEventListener('change', () => toggleTaskStatus(task.id));
        
        const taskTextContainer = document.createElement('div');
        taskTextContainer.className = 'task-text';
        
        if (editingTaskId === task.id) {
            // 编辑模式
            const editInput = document.createElement('input');
            editInput.type = 'text';
            editInput.value = task.text;
            editInput.className = 'edit-input';
            editInput.addEventListener('blur', () => finishEdit(task.id, editInput.value));
            editInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') finishEdit(task.id, editInput.value);
                if (e.key === 'Escape') cancelEdit();
            });
            taskTextContainer.appendChild(editInput);
            editInput.focus();
        } else {
            // 显示模式
            const taskTextSpan = document.createElement('span');
            taskTextSpan.textContent = task.text;
            taskTextContainer.appendChild(taskTextSpan);
            
            // 双击编辑
            taskTextSpan.addEventListener('dblclick', () => startEdit(task.id));
        }
        
        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'delete-btn';
        deleteBtn.textContent = '删除';
        deleteBtn.addEventListener('click', () => deleteTask(task.id));
        
        li.appendChild(checkbox);
        li.appendChild(taskTextContainer);
        li.appendChild(deleteBtn);
        
        taskList.appendChild(li);
    });
}

// 更新任务统计
function updateStats() {
    const totalTasks = tasks.length;
    const activeTasks = tasks.filter(task => !task.completed).length;
    
    taskCount.textContent = `${activeTasks} 个任务待完成`;
    
    // 只有当有已完成任务时显示清空按钮
    clearCompletedBtn.style.display = totalTasks > activeTasks ? 'block' : 'none';
}

// 添加新任务
function addTask() {
    const text = taskInput.value.trim();
    if (text) {
        const newTask = {
            id: Date.now().toString(),
            text: text,
            completed: false,
            createdAt: new Date().toISOString()
        };
        
        tasks.push(newTask);
        saveTasks();
        renderTasks();
        updateStats();
        taskInput.value = '';
    }
}

// 切换任务完成状态
function toggleTaskStatus(taskId) {
    const task = tasks.find(t => t.id === taskId);
    if (task) {
        task.completed = !task.completed;
        saveTasks();
        renderTasks();
        updateStats();
    }
}

// 删除任务
function deleteTask(taskId) {
    tasks = tasks.filter(task => task.id !== taskId);
    saveTasks();
    renderTasks();
    updateStats();
}

// 清空已完成任务
function clearCompletedTasks() {
    tasks = tasks.filter(task => !task.completed);
    saveTasks();
    renderTasks();
    updateStats();
}

// 开始编辑任务
function startEdit(taskId) {
    editingTaskId = taskId;
    renderTasks();
}

// 完成编辑
function finishEdit(taskId, newText) {
    newText = newText.trim();
    if (newText) {
        const task = tasks.find(t => t.id === taskId);
        if (task) {
            task.text = newText;
            saveTasks();
        }
    } else {
        // 如果编辑为空，则删除任务
        deleteTask(taskId);
    }
    editingTaskId = null;
    renderTasks();
}

// 取消编辑
function cancelEdit() {
    editingTaskId = null;
    renderTasks();
}

// 设置过滤器
function setFilter(filter) {
    currentFilter = filter;
    
    // 更新过滤按钮状态
    filterBtns.forEach(btn => {
        btn.classList.remove('active');
        if (btn.dataset.filter === filter) {
            btn.classList.add('active');
        }
    });
    
    renderTasks();
}

// 拖拽功能变量
let draggedItem = null;

// 处理拖拽开始
function handleDragStart(e) {
    draggedItem = this;
    e.dataTransfer.effectAllowed = 'move';
}

// 处理拖拽悬停
function handleDragOver(e) {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
}

// 处理拖拽放置
function handleDrop(e) {
    e.preventDefault();
    
    if (this !== draggedItem) {
        const draggedId = draggedItem.dataset.id;
        const targetId = this.dataset.id;
        
        const draggedIndex = tasks.findIndex(task => task.id === draggedId);
        const targetIndex = tasks.findIndex(task => task.id === targetId);
        
        // 重新排序任务数组
        const [removed] = tasks.splice(draggedIndex, 1);
        tasks.splice(targetIndex, 0, removed);
        
        saveTasks();
        renderTasks();
    }
    
    draggedItem = null;
}

// 设置事件监听器
function setupEventListeners() {
    // 添加任务按钮点击
    addTaskBtn.addEventListener('click', addTask);
    
    // 回车添加任务
    taskInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') addTask();
    });
    
    // 清空已完成按钮点击
    clearCompletedBtn.addEventListener('click', clearCompletedTasks);
    
    // 过滤器按钮点击
    filterBtns.forEach(btn => {
        btn.addEventListener('click', () => setFilter(btn.dataset.filter));
    });
    
    // 键盘快捷键支持
    document.addEventListener('keydown', (e) => {
        // Ctrl/Cmd + Enter 添加任务
        if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
            addTask();
        }
        // Esc 取消编辑
        if (e.key === 'Escape' && editingTaskId !== null) {
            cancelEdit();
        }
    });
}

// 启动应用
initApp();